package org.my.business.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.my.business.controller.app.dept.vo.AppDeptCreateVO;
import org.my.business.domain.bo.DeviceBo;
import org.my.business.domain.vo.DeviceVo;
import org.my.business.mapper.PcDeviceMapper;
import org.my.business.service.IAppDeptService;
import org.my.business.service.IDeviceService;
import org.my.common.core.constant.UserConstants;
import org.my.common.core.domain.R;
import org.my.common.core.exception.ServiceException;
import org.my.common.core.utils.MapstructUtils;
import org.my.common.core.utils.StringUtils;
import org.my.common.mybatis.core.page.PageQuery;
import org.my.common.satoken.utils.LoginHelper;
import org.my.system.domain.SysDept;
import org.my.system.domain.SysRole;
import org.my.system.domain.SysUser;
import org.my.system.domain.SysUserRole;
import org.my.system.domain.bo.SysDeptBo;
import org.my.system.mapper.SysDeptMapper;
import org.my.system.mapper.SysRoleMapper;
import org.my.system.mapper.SysUserMapper;
import org.my.system.mapper.SysUserRoleMapper;
import org.my.system.service.ISysDeptService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

/**
 * @author JohnnyKang
 */
@RequiredArgsConstructor
@Service
public class AppDeptServiceImpl implements IAppDeptService {

    private final ISysDeptService sysDeptService;

    private final SysDeptMapper sysDeptMapper;

    private final SysUserMapper sysUserMapper;

    private final SysRoleMapper sysRoleMapper;

    private final SysUserRoleMapper sysUserRoleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int create(AppDeptCreateVO createVO) {
        String tenantId = LoginHelper.getTenantId();
        Long userId = LoginHelper.getUserId();

        //获取该租户下的最大部门 也就是ParentId为0
        SysDept sysDept = sysDeptMapper.selectOne(Wrappers.lambdaQuery(SysDept.class).eq(SysDept::getTenantId, tenantId).eq(SysDept::getParentId, 0));
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(sysDept.getStatus())) {
            throw new ServiceException("部门停用，不允许新增");
        }
        //判断部门名称是否唯一
        boolean exists = sysDeptMapper.exists(new LambdaQueryWrapper<SysDept>()
            .eq(SysDept::getDeptName, createVO.getDeptName())
            .eq(SysDept::getParentId, sysDept.getDeptId()));
        if (exists) {
            throw  new ServiceException("新增部门'" + createVO.getDeptName() + "'失败，部门名称已存在");
        }
        //新增部门并设置为负责人
        SysDept dept = MapstructUtils.convert(createVO, SysDept.class);
        dept.setParentId(sysDept.getDeptId());
        dept.setOrderNum(1);
        dept.setLeader(userId);
        dept.setAncestors(sysDept.getAncestors() + StringUtils.SEPARATOR + dept.getParentId());
        sysDeptMapper.insert(dept);

        //设置角色
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(userId);
        SysRole sysRole = sysRoleMapper.selectOne(Wrappers.lambdaQuery(SysRole.class).eq(SysRole::getTenantId, tenantId).eq(SysRole::getRoleKey, "dept_admin").eq(SysRole::getDelFlag, "0"));
        if(ObjectUtil.isNull(sysRole)){
            SysRole role = new SysRole();
            role.setTenantId(tenantId);
            role.setRoleKey("dept_admin");
            role.setRoleName("部门管理员");
            role.setDataScope("4");
            role.setRoleSort(1);
            role.setStatus("0");
            sysRoleMapper.insert(role);
            sysUserRole.setRoleId(role.getRoleId());
        }else{
            sysUserRole.setRoleId(sysRole.getRoleId());
        }
        sysUserRoleMapper.insert(sysUserRole);

        //部门创建成功后 把这个人设置为在这个部门下
        SysUser sysUser = new SysUser();
        sysUser.setDeptId(dept.getDeptId());
        sysUser.setUserId(LoginHelper.getUserId());
        return sysUserMapper.updateById(sysUser);
    }
}
